<template>
  <div class="dataBase">
    <ContentWrap>
      <el-form label-width="100px" ref="formRef" :model="searchValue" @submit.prevent>
        <el-row>
          <el-col :span="6">
            <el-form-item label="报表名称：" prop="name">
              <ns-input
                @keyup.enter="search"
                v-model="searchValue.name"
                clearable
                placeholder="请输入报表名称"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="text-right">
            <el-button @click="search" type="primary" v-hasPermi="['amp:report-manage:search']"
              >搜索</el-button
            >
            <el-button @click="searchReset" plain v-hasPermi="['amp:report-manage:search']"
              >重置</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <el-form-item>
        <el-button
          type="primary"
          @click="openForm('create')"
          v-hasPermi="['amp:report-manage:add']"
        >
          新增</el-button
        >
      </el-form-item>
      <AsyncTable
        v-bind="tableInfo"
        ref="tableRef"
        :fetchData="fetchData"
        @selection-change="changeTable"
      />
    </ContentWrap>
    <reportForm ref="standardsFormRef" @success="getList" />
    <div class="mt-1000px">
      <div id="displayChart" v-if="currentId" ref="reportChartRef">
        <DisplayChart :reportId="currentId" />
      </div>
    </div>
  </div>
</template>

<script setup lang="tsx">
import { ElMessage } from 'element-plus'
import AsyncTable from '@/components/AsyncTable'
import DisplayChart from '../display/index2.vue'
import { useRouter } from 'vue-router'
import * as reportManageApi from '@/api/report/reportManage/index'
import reportForm from './components/reportForm.vue'
import { ComponentInternalInstance, getCurrentInstance } from 'vue'
import printJS from 'print-js'
import download from '@/utils/download'
import html2canvas from 'html2canvas'
import { ElLoading } from 'element-plus'
import { checkPermi } from '@/utils/permission'

const message = useMessage() // 消息弹窗
const tableRef = ref()
const formRef = ref()
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const router = useRouter()
const route = useRoute()
const ids = ref<string[]>([])
const reportChartRef = ref()
const timeMap = new Map([
  [0, '全部'],
  [1, '本日'],
  [2, '本周'],
  [3, '本月'],
  [4, '本年']
])

/**
 * @description: 选取列表时获取列表id
 * @param {*} val
 */
const changeTable = (val) => {
  ids.value = []
  val.map((item) => {
    ids.value.push(item.id)
  })
}
const searchReset = () => {
  formRef.value.resetFields()
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
const searchValue = ref({
  name: ''
})

const search = () => {
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
const tableInfo = reactive({
  columns: [
    {
      type: 'index'
    },
    { label: '报表名称', prop: 'name' },
    { label: '报表模板', prop: 'temp' },
    {
      label: '默认期间',
      render: ({ row }) => {
        return <>{timeMap.get(row.defaultTime)}</>
      }
    },
    {
      label: '首页展示',
      render: ({ row }) => {
        return (
          <>
            <el-switch
              v-model={row.showHomePage}
              active-value={1}
              inactive-value={0}
              disabled={row.showHomePage == 1}
              onChange={() => handleChangeState(row)}
            />
          </>
        )
      }
    },
    {
      label: '报表展示',
      render: ({ row }) => {
        return (
          <>
            <el-switch
              v-model={row.showStatus}
              active-value={1}
              inactive-value={0}
              disabled={row.showStatus == 1}
              onChange={() => changeShowStatus(row)}
            />
          </>
        )
      }
    },
    { label: '创建时间', prop: 'createTime' },
    {
      label: '操作项',
      width: '250px',
      render: ({ row }) => {
        return (
          <>
            {checkPermi(['amp:report-manage:add']) && (
              <el-dropdown
                style="vertical-align:bottom"
                class="mr-10px"
                v-slots={{
                  dropdown: () => (
                    <el-dropdown-menu>
                      <el-dropdown-item>
                        <el-button
                          link
                          type="primary"
                          onClick={() => {
                            downloadPdf(row.id)
                          }}
                        >
                          PDF
                        </el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button
                          link
                          type="primary"
                          onClick={() => {
                            downloadExcel(row.id)
                          }}
                        >
                          EXCEL
                        </el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button
                          link
                          type="primary"
                          onClick={() => {
                            downloadHtml(row.id)
                          }}
                        >
                          HTML
                        </el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button
                          link
                          type="primary"
                          onClick={() => {
                            downloadWord(row.id)
                          }}
                        >
                          WORD
                        </el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button
                          link
                          type="primary"
                          onClick={() => {
                            downloadPNG(row.id)
                          }}
                        >
                          PNG
                        </el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button
                          link
                          type="primary"
                          onClick={() => {
                            downloadJPG(row.id)
                          }}
                        >
                          JPG
                        </el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button
                          link
                          type="primary"
                          onClick={() => {
                            downloadBMP(row.id)
                          }}
                        >
                          BMP
                        </el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button
                          link
                          type="primary"
                          onClick={() => {
                            downloadTxt(row.id)
                          }}
                        >
                          TXT
                        </el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button
                          link
                          type="primary"
                          onClick={() => {
                            downloadSVG(row.id)
                          }}
                        >
                          SVG
                        </el-button>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  )
                }}
              >
                <el-button link type="primary">
                  下载
                </el-button>
              </el-dropdown>
            )}
            {checkPermi(['amp:report-manage:detail']) && (
              <el-button
                link
                type="primary"
                onClick={() => {
                  editReport(row.id)
                }}
              >
                编辑
              </el-button>
            )}
            {checkPermi(['amp:report-manage:detail']) && (
              <el-button
                link
                type="primary"
                onClick={() => {
                  checkReport(row.id)
                }}
              >
                查看
              </el-button>
            )}
            {checkPermi(['amp:report-manage:delete']) && (
              <ns-button
                style="margin-left:6px"
                link
                type="danger"
                disabled={row.showStatus == 1}
                confirm
                onClick={() => {
                  del(row)
                }}
              >
                删除
              </ns-button>
            )}
          </>
        )
      }
    }
  ],
  data: []
})

const currentId = ref()
const downloadPdf = async (id) => {
  currentId.value = id
  // 在页面显示需打印区域来获取dom
  await nextTick()
  document.querySelector('#displayChart').style.display = 'block'
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  setTimeout(() => {
    loading.close()
    // 将Canvas转换为PDF
    html2canvas(reportChartRef.value).then((canvas) => {
      const pngUrl = canvas.toDataURL('image/png')
      printJS({
        printable: pngUrl,
        type: 'image',
        documentTitle: '',
        header: null,
        base64: true,
        style: `@media print { @page {size: auto; margin: 0; } body{margin:0; padding: 0;}}`
        // imageStyle: 'width: 100%; height: 100vh; margin:0; padding: 0;'
      })
    })

    // 获取打印内容后隐藏dom
    document.querySelector('#displayChart').style.display = 'none'
  }, 2000)
}

const downloadPNG = async (id) => {
  currentId.value = id
  // 在页面显示需打印区域来获取dom
  await nextTick()
  document.querySelector('#displayChart').style.display = 'block'
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  setTimeout(() => {
    loading.close()
    html2canvas(reportChartRef.value).then((canvas) => {
      const pngUrl = canvas.toDataURL('image/png')
      console.log('pngUrl', pngUrl)
      const a = document.createElement('a')
      a.href = pngUrl
      a.download = '报表.png'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    })
    // 获取打印内容后隐藏dom
    document.querySelector('#displayChart').style.display = 'none'
  }, 2000)
}
const downloadJPG = async (id) => {
  currentId.value = id
  // 在页面显示需打印区域来获取dom
  await nextTick()
  document.querySelector('#displayChart').style.display = 'block'
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  setTimeout(() => {
    loading.close()
    html2canvas(reportChartRef.value).then((canvas) => {
      const pngUrl = canvas.toDataURL('image/png')
      console.log('pngUrl', pngUrl)
      const a = document.createElement('a')
      a.href = pngUrl
      a.download = '报表.jpg'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    })
    // 获取打印内容后隐藏dom
    document.querySelector('#displayChart').style.display = 'none'
  }, 2000)
}
const downloadBMP = async (id) => {
  currentId.value = id
  // 在页面显示需打印区域来获取dom
  await nextTick()
  document.querySelector('#displayChart').style.display = 'block'
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  setTimeout(() => {
    loading.close()
    html2canvas(reportChartRef.value).then((canvas) => {
      const pngUrl = canvas.toDataURL('image/png')
      console.log('pngUrl', pngUrl)
      const a = document.createElement('a')
      a.href = pngUrl
      a.download = '报表.bmp'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    })
    // 获取打印内容后隐藏dom
    document.querySelector('#displayChart').style.display = 'none'
  }, 2000)
}

const downloadHtml = async (id) => {
  currentId.value = id
  // 在页面显示需打印区域来获取dom
  await nextTick()
  document.querySelector('#displayChart').style.display = 'block'
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  setTimeout(() => {
    loading.close()
    html2canvas(reportChartRef.value).then((canvas) => {
      const pngUrl = canvas.toDataURL('image/png')
      const htmlContent = `
        <!DOCTYPE html>
        <html lang="en">
        <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Vue Template</title>
        </head>
        <body>
          <img src="${pngUrl}" alt="" />
        </body>
        </html>
      `

      exportToHTML(htmlContent, '报表.html')
    })
    // 获取打印内容后隐藏dom
    document.querySelector('#displayChart').style.display = 'none'
  }, 2000)
}

const downloadSVG = async (id) => {
  currentId.value = id
  // 在页面显示需打印区域来获取dom
  await nextTick()
  document.querySelector('#displayChart').style.display = 'block'
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  setTimeout(() => {
    loading.close()
    html2canvas(reportChartRef.value).then((canvas) => {
      const pngUrl = canvas.toDataURL('image/png')
      const svgContent = `
        <svg xmlns="http://www.w3.org/2000/svg" width="${canvas.width}" height="${canvas.height}">
          <image href="${pngUrl}" width="${canvas.width}" height="${canvas.height}" />
        </svg>
      `

      const blob = new Blob([svgContent], { type: 'image/svg+xml' })
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = '报表.svg'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    })
    // 获取打印内容后隐藏dom
    document.querySelector('#displayChart').style.display = 'none'
  }, 2000)
}

const downloadWord = async (id) => {
  currentId.value = id
  // 在页面显示需打印区域来获取dom
  await nextTick()
  document.querySelector('#displayChart').style.display = 'block'
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  setTimeout(() => {
    loading.close()
    html2canvas(reportChartRef.value).then(async (canvas) => {
      const pngUrl = canvas.toDataURL('image/png')
      // console.log('pngUrl',pngUrl)
      // const data = await reportManageApi.reportManageReport({ id: id, type: 'word',data:pngUrl })
      // download.excel(data, '报表.docx')
      const htmlContent = `
        <!DOCTYPE html>
        <html lang="en">
        <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Vue Template</title>
        </head>
        <body>
          <img src="${pngUrl}" alt="" style="width: 500px; height: auto;"/>
        </body>
        </html>
      `
      // var htmlContent = `<html><body><img src="${pngUrl}" style='width: 210mm; height: auto;' /></body></html>`
      // var htmlContent = `<html><body><table style='width: 100%;'><tr><td style='width: " + a4WidthPx + "px;'><img src="${pngUrl}" style='width: 100%; height: auto;' /></td></tr></table></body></html>`

      // 使用Blob对象创建Word文档
      var blob = new Blob(['\ufeff', htmlContent], {
        type: 'application/msword'
      })
      // 创建一个链接并下载Word文档
      var url = URL.createObjectURL(blob)
      var link = document.createElement('a')
      link.href = url
      link.download = 'document.doc'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    })
    // 获取打印内容后隐藏dom
    document.querySelector('#displayChart').style.display = 'none'
  }, 2000)
}

function exportToHTML(htmlContent, filename) {
  // 创建一个Blob对象，将HTML内容包装在其中
  const blob = new Blob([htmlContent], { type: 'text/html' })

  // 创建一个URL对象，用于生成下载链接
  const url = URL.createObjectURL(blob)

  // 创建一个<a>元素用于下载链接
  const a = document.createElement('a')
  a.href = url
  a.download = filename || 'template.html' // 设置默认文件名为template.html
  a.style.display = 'none'

  // 将<a>元素添加到DOM中，并模拟点击以下载文件
  document.body.appendChild(a)
  a.click()

  // 清理工作：移除<a>元素和URL对象
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

const downloadExcel = async (id) => {
  // 导出的二次确认
  // await message.exportConfirm()
  // 发起导出
  const data = await reportManageApi.reportManageReport({ id: id, type: 'excel' })
  download.excel(data, '报表.xlsx')
}
const downloadTxt = async (id) => {
  // 导出的二次确认
  // await message.exportConfirm()
  // 发起导出
  const data = await reportManageApi.reportManageReport({ id: id, type: 'text' })
  download.excel(data, '报表.txt')
}

const downloadNo = () => {
  message.warning('暂不支持当前格式导出')
}

const del = (row) => {
  proxy?.$modal
    .confirm(`确定要删除该数据吗？`)
    .then(() => {
      reportManageApi.reportManageDel(row.id).then((response) => {
        console.log('response', response)
        tableRef.value.fetchData()
        ElMessage.success('操作成功')
      })
    })
    .catch(() => {})
}
const changeShowStatus = (row) => {
  if (row.id) {
    reportManageApi.reportManageOpen(row.id).then((response) => {
      setTimeout(() => {
        tableRef.value.fetchData()
      }, 1000)
      ElMessage.success('操作成功')
    })
  }
}

const handleChangeState = async (row) => {
  if (row.id) {
    reportManageApi.reportManageOpenHomePage(row.id).then((response) => {
      setTimeout(() => {
        tableRef.value.fetchData()
      }, 1000)
      ElMessage.success('操作成功')
    })
  }
  // const state = row.showHomePage
  // try {
  //   // 修改状态的二次确认
  //   if(state === 0){
  //     const content = '是否确定展示在首页上！'
  //     await message.confirm(content)
  //   }
  //   // 发起修改状态
  //   await reportManageApi.reportManageOpenHomePage(row.id)
  //   // 刷新列表
  //   await getList()
  // } catch {
  //   // 取消后，进行恢复按钮
  //   row.showHomePage = state === 0 ? 0 : 1
  // }
}

const pageParams = ref({
  page: 1,
  pageSize: 10
})
const fetchData = async ({ page, pageSize }) => {
  pageParams.value = {
    page,
    pageSize
  }
  const { data, count } = await reportManageApi.reportManagePage({
    page,
    pageSize,
    ...searchValue.value
  })
  // currentId.value = data[0].id
  return { data, count }
}

/** 添加/修改操作 */
const standardsFormRef = ref()
const openForm = (type: string, id?: number) => {
  standardsFormRef.value.open(type, id)
}

const editReport = (id) => {
  router.push({
    path: '/report/reportEdit2',
    query: {
      id
    }
  })
}
const checkReport = (id) => {
  router.push({
    path: '/report/reportDetail',
    query: {
      id
    }
  })
}

const getList = () => {
  tableRef.value.fetchData()
}

onMounted(() => {
  if (route.query?.isFromEdit == 'true') {
    standardsFormRef.value.open('add', 0, route.query)
  }
})
</script>

<style lang="scss">
.dataBase {
  .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: inline-flex;
    align-items: center;
    line-height: 23px;
    padding-left: 12px;
  }
  .el-form .el-select {
    width: 100%;
  }
  :deep(.hide-expand .cell) {
    display: none;
  }
  :deep(.el-form .el-cascader) {
    width: 100%;
  }
  :deep(.operate-btn .el-button.is-text) {
    padding: 0 10px 0 0;
  }
  .el-dropdown-link:focus {
    outline: none;
  }
}
#displayChart {
  width: 1200px;
}
</style>
